﻿using UnityEngine;
using System.Collections;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
using System;
using System.IO;
using System.Net;
using System.Globalization;
using LitJson;
using Random = System.Random;
using UnityEngine.SceneManagement;

//using UnityEngine.SceneManagement;



public class APaymentHelperDemo : MonoBehaviour
{

    Rect windowRect = new Rect(20, 20, 400, 600);
    string game_object = "Main Camera";

    void OnGUI()
    {
        windowRect = GUI.Window(0, windowRect, DoMyWindow, game_object);
    }

    void Start()
    {
        //Debug.Log (gameObject);
        //设置登录监听回调，需要在登录前调用，参数gameobject是脚本绑定的游戏对象
        APaymentHelper.Instance.SetOnLoginListener(game_object);
    }

    void Update()
    {
        //使用sdk内置的退出框
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            APaymentHelper.Instance.Exit();
        }
    }

    void DoMyWindow(int windowID)
    {

        if (GUI.Button(new Rect(10, 30, 100, 60), "Login"))
        {
            //登录接口,登录后会在设置监听的游戏对象绑定的脚本下LoginResult方法触发相应的回调。
            APaymentHelper.Instance.Login();
        }
        if (GUI.Button(new Rect(150, 30, 100, 60), "Logout"))
        {
            //登出接口,登录后会在设置监听的游戏对象绑定的脚本下LoginResult方法触发相应的回调。
            APaymentHelper.Instance.Logout();
        }
        if (GUI.Button(new Rect(10, 110, 100, 60), "100Gold"))
        {
            Pay();
        }
        if (GUI.Button(new Rect(150, 110, 100, 60), "Sync"))
        {

            //同步用户数据到sdk后台，需要在登录成功后，每次用户信息变化时回传给sdk.
            JsonData obj = new JsonData();
            obj["role_id"] = "1001";  //游戏角色id,必传
            obj["role_name"] = "hello";//游戏角色名字，若没有传""
            obj["role_level"] = "20";//游戏等级，若没有传0
            obj["server_id"] = "21";//传游戏区的id
            obj["server_name"] = "游戏1区";//游戏区的名字
            obj["vip"] = "1";//游戏vip等级
            obj["party_name"] = "帮派";//游戏帮派
            obj["camp"] = "阵营";//游戏阵营
            obj["ext"] = "ext"; //设置额外的参数，若没有传“”

            string sync_data = obj.ToJson();

            APaymentHelper.Instance.Sync(sync_data, game_object);

        }

        if (GUI.Button(new Rect(10, 190, 100, 60), "checkpay"))
        {
            //检测支付方式
            APaymentHelper.Instance.CheckPay(game_object);
        }

        if (GUI.Button(new Rect(150, 190, 100, 60), "Exit"))
        {
            //游戏退出接口
            APaymentHelper.Instance.Exit();
        }

        if (GUI.Button(new Rect(10, 270, 100, 60), "GooglePay"))
        {
            //检测支付方式
            GooglePay();
        }

        //GUI.TextField(new Rect(10,270,100,60),"123",15);

    }

    void Pay()
    {
        JsonData obj = new JsonData();
        obj["subject"] = "100Gold"; // 商品标题
        obj["body"] = "购买100Gold"; // 商品详细内容
        obj["total_amount"] = "1"; //支付金额，单位 元
        obj["attach"] = "扩展参数"; //设置额外参数，用于回传给游戏后台
        obj["role_id"] = "1001";//游戏角色的id
        obj["role_name"] = "小明";//游戏角色名字
        obj["server_id"] = "1";//传游戏区的id
        //obj["bundle"] = "com.98gam.slot.gold1";//游戏道具品项，如 60元宝对应的编号
        obj["bundle"] = "com.app980x.gold.cq1";//游戏道具品项，如 60元宝对应的编号
        obj["out_trade_no"] = GetOutTradeNo();//订单号

        string payjson = obj.ToJson();
        Debug.Log(payjson);
        APaymentHelper.Instance.Pay(payjson, game_object);
    }

    void GooglePay()
    {
        JsonData obj = new JsonData();
        obj["subject"] = "100Gold"; // 商品标题
        obj["body"] = "购买100Gold"; // 商品详细内容
        obj["total_amount"] = "1"; //支付金额，单位 元
        obj["attach"] = "扩展参数"; //设置额外参数，用于回传给游戏后台
        obj["role_id"] = "1001";//游戏角色的id
        obj["role_name"] = "小明";//游戏角色名字
        obj["server_id"] = "1";//传游戏区的id
        obj["bundle"] = "com.app980x.gold.google1";//游戏道具品项，如 60元宝对应的编号
        obj["out_trade_no"] = GetOutTradeNo();//订单号

        string payjson = obj.ToJson();
        Debug.Log(payjson);
        APaymentHelper.Instance.GooglePay(payjson, game_object);
    }

    public string GetTimeStamp()
    {
        TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);

        return Convert.ToInt64(ts.TotalSeconds).ToString();
    }

    public string GetOutTradeNo()
    {
        string format = "MMddHHmmss";
        DateTime date = DateTime.Now;
        string key = date.ToString(format, DateTimeFormatInfo.InvariantInfo);
        Random r = new Random();
        key = key + r.Next();
        key = key.Substring(0,15);
        //key = key.substring(0, 15);
        return key;
    }



    /*
	 * 支付回调
	 * 
	 * 1004:支付成功
	 * {"data":"{\"alipay_trade_app_pay_response\":{\"code\":\"10000\",\"msg\":\"Success\",\"app_id\":\"2018031002349616\",\"auth_app_id\":\"2018031002349616\",\"charset\":\"UTF-8\",\"timestamp\":\"2018-05-29 18:01:54\",\"total_amount\":\"0.01\",\"trade_no\":\"2018052921001004910595768087\",\"seller_id\":\"2088121362660304\",\"out_trade_no\":\"0529180056-4884\"},\"sign\":\"IutHVLXrpfLCfAx/LGAEA4JzxS75pM+2rMfOtWs1K5aW3phAxNw+A5AQIqI4tGBSEnm1rBu/e3dMBbc6QOLh4M27p++pt7Xrkxu+CKWJXo1XtAxK9tCF3/87icduhb9tuLybiuEHEb8Jc0IxJgRkxYd5YcddiHeQbZAA/VfKeSeuGVQyX/FnK+2hr86UgSNPwh5MP4j5aQmsLIYSyRQso8mXnt/Rd3G4bPtPWXB3M8d0xu5RIQdxlBCAGrcsj1Yb5LVXT+blH2uh2I8QbWNGbdafuDmwGnVW7GcQeBYU/ihV89j69j8c4j7GhI3VzzZHS/kBOq0s5h+xUO4iUyK+/w\u003d\u003d\",\"sign_type\":\"RSA2\"}",
	 * "msg":"处理成功","ret":1004}
	 * 
     *  1005:支付失败
      * 返回实例
	 * {"data":"","msg":"支付失败","ret":1005}
	 */
    void PayResult(string result)
    {
        Debug.Log("------------PayResult=" + result);
        JsonData jo = JsonMapper.ToObject(result);
        string ret = jo["ret"].ToString();
        string msg = jo["msg"].ToString();
        string data = jo["data"].ToString();
        Debug.Log("---------Pay_msg=" + msg);
        Debug.Log("---------Pay_data=" + data);
        if (ret.Equals("1004"))
        {
            Debug.Log("支付成功");
        }
        else
        {
            Debug.Log("支付失败");
        }
    }

    /*
	 * 登录登出回调
	 * 登录返回码
	 * 
	 * 1001 登录成功
	 * {"data":{"access_token":"m22Q6RbzKwcOtPlEDxINEhzlUYLBysSv","id":152,"is_certification":0,"username":"980x_862694"},"msg":"登录成功","ret":1001}
	 * 1002 登录失败
	 * {"data":"","msg":"登录失败","ret":1002}
	 * 1003 退出登录
	 * {"data":"","msg":"登出成功","ret":1003}
	 * 
	 */
    void LoginResult(string result)
    {
        Debug.Log("------------LoginResult=" + result);
        //转为json对象
        JsonData jo = JsonMapper.ToObject(result);
        string ret = jo["ret"].ToString();
        string msg = jo["msg"].ToString();
        string data = jo["data"].ToString();
        Debug.Log("---------Login_msg=" + msg);
        Debug.Log("---------Login_data=" + data);
        if (ret.Equals("1001"))
        {
            //SceneManager.LoadScene("game");
            Debug.Log("登录成功");
        }
        else if (ret.Equals("1002"))
        {
            Debug.Log("登录失败");
        }
        else if (ret.Equals("1003"))
        {
            Debug.Log("登出成功");
        }
    }

    void CheckPayResult(string result)
    {
        Debug.Log("------------CheckPayResult=" + result);
        //转为json对象
        JsonData jo = JsonMapper.ToObject(result);
        string ret = jo["ret"].ToString();
        JsonData data = jo["data"];

        if (ret.Equals("1006"))
        {
            string pay_state = data["pay_state"].ToString();
            if (pay_state.Equals("0"))
            {
                Pay();
            }
            Debug.Log("成功:" + pay_state);
        }
        else
        {
            Debug.Log("失败");
        }

    }

    void SyncInfoResult(string result)
    {
        Debug.Log("------------SyncInfoResult=" + result);
        //转为json对象
        JsonData jo = JsonMapper.ToObject(result);
        string ret = jo["ret"].ToString();
        if (ret.Equals("1008"))
        {
            Debug.Log("sync_success");
        }
        else
        {
            Debug.Log("sync_fail");
        }
    }
}
